package com.dyh.quickdemo.demos.threBank;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/*
@Author=Joey Wheeler
@Date=2020/10/30 10:13
*/
@Slf4j
public class ThreBankDemo {
    /*TryableSemaphore*/
    public static void main(String[] args) throws InterruptedException {
        /*8*/
//        Runtime runtime = Runtime.getRuntime();
//        System.out.println();
      //  System.out.println(Runtime.getRuntime().availableProcessors());
        int core = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        Semaphore s1 = new Semaphore(1);

        log.info("s1.acquire 1 start");
        s1.acquire();
        log.info("s1.acquire 1 end availablePermits={}",s1.availablePermits());


        log.info("s1.acquire 2 start");
        s1.acquire();
        log.info("s1.acquire 2 end");


        executorService.submit(r1);
        s1.release();
        s1.release();


        Semaphore s2 = new Semaphore(5);
        s2.acquire(2);
        executorService.submit(r2);
        executorService.submit(r2);
        s1.release(2);

        executorService.shutdown();//不然主线程一直在
    }

    public static Runnable r1 = ()-> {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"r1");
    };
    public static Runnable r2 = ()-> {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"r2");
    };
}
